package jsp.binalee;

import java.sql.Connection;
import java.util.ArrayList;

public class ConnectionPool {
	private static ConnectionPool cp = null;
	private ArrayList<Connection> connList = null;
	private ConnectionFactory cf = null;
	
	private ConnectionPool(){
		cf = ConnectionFactory.getDefaultFactory();
		connList = new ArrayList<Connection>();
		
		for(int i = 0; i < 5; i++){
			connList.add(cf.createConnection());
		}		
	}
	
	public static ConnectionPool getDefaultConnection(){
		if(cp == null)
			cp = new ConnectionPool();
		
		return cp;
	}
	
	public synchronized Connection getConnection(){
		if(connList.size() <= 0)
			try {
				this.wait();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		
		return connList.remove(0);
	}
	
	public synchronized void returnConnection(Connection conn){
		connList.add(conn);
		this.notifyAll();
	}
}
